import 'dart:async';
import 'dart:io';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:preload_page_view/preload_page_view.dart';
import 'package:provider/provider.dart';
import 'package:wallpaper/components/AlertDialog/loading_dialog.dart';
import 'package:wallpaper/components/button/action_icon_btn.dart';
import 'package:wallpaper/components/button/normal_button.dart';
import 'package:wallpaper/components/images/CustomImageCacheManager.dart';
import 'package:wallpaper/components/images/image_view_item.dart';
import 'package:wallpaper/db/love_database.dart';
import 'package:wallpaper/generated/l10n.dart';
import 'package:wallpaper/tools/down_image.dart';
import 'package:wallpaper_manager_plus/wallpaper_manager_plus.dart';

// ignore: must_be_immutable
class ImageView extends StatefulWidget {
  final List images;
  int selectedIndex;
  final VoidCallback resetGetdata;
  bool isMobile;
  ImageView({
    super.key,
    required this.images,
    required this.selectedIndex,
    required this.resetGetdata,
    this.isMobile = false,
  });

  @override
  State<ImageView> createState() => _ImageViewState();
}

class ImageSizeInfo {
  final int index;
  final int width;
  final int height;
  ImageSizeInfo({
    required this.index,
    required this.width,
    required this.height,
  });
}

class _ImageViewState extends State<ImageView> {
  bool isLove = false;
  double iconSize = 30;
  late PreloadPageController _pageController;
  double _currentScale = 1.0; // 跟踪图缩放比例
  bool isOperation = true;
  List images = [];
  int active = 0;
  Timer? loadTimer;
  final cacheManager = CustomImageCacheManager.instance.cacheManager;
  ImageSizeInfo sizeInfo = ImageSizeInfo(index: -1, width: 0, height: 0);
  bool change = false;

  void changeScale(double scale) {
    setState(() {
      _currentScale = scale;
    });
  }

  Future<void> isLoveGet() async {
    try {
      bool res = await context.read<LoveDatabase>().isLove(widget.isMobile
          ? images[active].largePath
          : images[active].smallPath);
      if (mounted) {
        setState(() {
          isLove = res;
        });
      }
    } catch (e) {
      // 处理可能的异常，防止崩溃
      debugPrint("isLoveGet error: $e");
    }
  }

  Future<void> downLoad() async {
    await DownImage.downloadNetworkImage(images[active].largePath, context);
  }

  Future<void> shareImage() async {
    Clipboard.setData(ClipboardData(text: images[active].largePath));
    BotToast.showText(text: S.of(context).s2);
  }

  Future<void> setWallpaper() async {
    final int? location = await showDialog<int>(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.black.withOpacity(0.7),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        elevation: 8,
        child: Padding(
          padding: const EdgeInsets.all(18.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _buildListTitle(
                  S.of(context).b1, S.of(context).b2, Icons.phone_android, () {
                Navigator.pop(context, WallpaperManagerPlus.homeScreen);
              }),
              _buildListTitle(
                  S.of(context).b3, S.of(context).b4, Icons.lock_rounded, () {
                Navigator.pop(context, WallpaperManagerPlus.lockScreen);
              }),
              _buildListTitle(
                  S.of(context).b5, S.of(context).b6, Icons.phonelink_setup,
                  () {
                Navigator.pop(context, WallpaperManagerPlus.bothScreens);
              }),
              const SizedBox(height: 10),
              NormalButton(
                title: S.of(context).b7,
                onPressed: () {
                  Navigator.pop(context);
                },
                bgColor: Colors.white.withOpacity(0.08),
                textColor: Colors.white,
              ),
            ],
          ),
        ),
      ),
    );

    if (location == null) return;

    final closeLoading = LoadingDialog.showLoading(
      context: context,
      message: S.of(context).s3,
    );
    try {
      final path = await DownImage().setWallpaper(images[active].largePath);
      if (path == null) {
        return;
      }
      await WallpaperManagerPlus().setWallpaper(File(path), location);
      BotToast.showText(text: S.of(context).s4);
    } catch (e) {
      BotToast.showText(text: S.of(context).s5, contentColor: Colors.red);
    } finally {
      closeLoading();
    }
  }

  void changeLove() async {
    String url = images[active].largePath;
    String cover = images[active].smallPath;
    String tags = images[active].tags;
    if (isLove) {
      setState(() {
        isLove = false;
      });
      context.read<LoveDatabase>().addLove(
            widget.isMobile ? url : cover,
            url,
            tags,
            'image',
            'vertical',
          );
      widget.resetGetdata();
      return;
    }
    try {
      if (images[active].width != null) {
        int width = images[active].width!;
        int height = images[active].height!;
        context.read<LoveDatabase>().addLove(
              widget.isMobile ? url : cover,
              url,
              tags,
              'image',
              width > height ? 'horizontal' : 'vertical',
            );
        setState(() {
          isLove = true;
        });
      } else {
        if (sizeInfo.index == active) {
          int width = sizeInfo.width;
          int height = sizeInfo.height;
          context.read<LoveDatabase>().addLove(
                widget.isMobile ? url : cover,
                url,
                tags,
                'image',
                width > height ? 'horizontal' : 'vertical',
              );
          setState(() {
            isLove = true;
          });
        } else {
          BotToast.showText(text: '图片加载中，请稍后');
        }
      }
    } catch (e) {
      if (e.toString().contains('Love')) {
        int width = sizeInfo.width;
        int height = sizeInfo.height;
        setState(() {
          isLove = true;
        });
        context.read<LoveDatabase>().addLove(
              widget.isMobile ? url : cover,
              url,
              tags,
              'image',
              width > height ? 'horizontal' : 'vertical',
            );
        widget.resetGetdata();
        return;
      }
    }
  }

  @override
  void initState() {
    super.initState();
    _pageController = PreloadPageController(initialPage: widget.selectedIndex);
    images = widget.images;
    active = widget.selectedIndex;

    loadTimer = Timer(const Duration(milliseconds: 300), () {
      if (mounted) {
        setState(() {
          isLoveGet();
        });
      }
    });
  }

  @override
  void dispose() {
    // 确保释放页面控制器资源
    _pageController.dispose();
    loadTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          setState(() {
            isOperation = !isOperation;
          });
        },
        child: Stack(
          children: [
            _buildImageView(),
            _buildOperationBar(),
          ],
        ),
      ),
    );
  }

  Widget _buildImageView() {
    return Container(
      color: Colors.black,
      child: PreloadPageView.builder(
        controller: _pageController,
        scrollDirection: Axis.vertical,
        physics: _currentScale != 1
            ? const NeverScrollableScrollPhysics() // 缩放时禁用滚动
            : const ClampingScrollPhysics(), // 正常状态允许滚动
        itemCount: widget.images.length,
        itemBuilder: (context, index) {
          return ImageViewItem(
            smallPath: widget.images[index].smallPath,
            largePath: widget.images[index].largePath,
            isMobile: widget.isMobile,
            tags: widget.images[index].tags,
            changeScale: changeScale,
            getSize: (w, h) {
              if (index == active) {
                sizeInfo = ImageSizeInfo(index: index, width: w, height: h);
              }
            },
          );
        },
        onPageChanged: (index) {
          if (mounted) {
            setState(() {
              active = index;
            });
            isLoveGet();
          }
        },
      ),
    );
  }

  Widget _buildOperationBar() {
    return Positioned(
      top: 0,
      right: 12,
      bottom: 0,
      child: Center(
        child: AnimatedSlide(
          offset: isOperation ? Offset.zero : const Offset(1.5, 0),
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            spacing: 5,
            children: [
              ActionIconButton(
                icon: Icons.phone_android_rounded,
                onTap: setWallpaper,
                color: Colors.white,
              ),
              ActionIconButton(
                icon: Icons.share,
                onTap: shareImage,
                color: Colors.white,
              ),
              ActionIconButton(
                icon: Icons.download,
                onTap: downLoad,
                color: Colors.white,
              ),
              ActionIconButton(
                icon: isLove ? Icons.favorite : Icons.favorite_border,
                onTap: changeLove,
                color: isLove ? Colors.red : Colors.white,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildListTitle(
      String title, String subtitle, IconData icon, Function onTap) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 6),
      child: ListTile(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
        tileColor: Colors.white.withOpacity(0.07),
        title: Text(title,
            style: const TextStyle(
                color: Colors.white, fontWeight: FontWeight.bold)),
        subtitle: Text(subtitle,
            style: const TextStyle(color: Colors.white70, fontSize: 13)),
        leading: Icon(icon, color: Colors.white),
        trailing:
            const Icon(Icons.arrow_forward_ios, color: Colors.white, size: 18),
        onTap: () => onTap(),
      ),
    );
  }
}
